# -*- coding: UTF-8 -*-
"""
@Project :xlx-fastapi
@File    :admin_log_dao.py
@Author  :xlx-ali
@Date    :2024/06/24 15:44 星期一
"""
from datetime import datetime
import time
from typing import Union
from sqlalchemy import desc, select

from app.types import apiproto

from .base_dao import getDatabaseSession
from app.dao.models import XlxAdminLog


class AdminLogQueryDao(object):
    """管理员日志查询类dao"""
    pass


class AdminLogOperateDao(object):
    """操作管理员日志相关dao"""

    @classmethod
    def writeLog(cls, content: Union[str, list], admin_info: apiproto.AdminUserDetailProto, ip: str, ip_addr: str, is_login: int = 0, type: int = 1):
        """
        写入日志

        Args:
            content (str|list): 日志内容
            admin_info (AdminUserDetailProto): admin信息
            ip (str): IP
            ip_addr (str): 地址
            is_login (int): 是否登录0|否；1|是
            type (int): 操作类型[0:-;1:常规;2:新增;3:修改;4:删除;5:业务;6:审核;7:锁定;]
        Returns:
            bool|float|int|str

        Author:
            edc
        """
        if isinstance(content, list):
            log_all = []
            for one in content:
                one = one.strip()
                one = cls.mb_rtrim(one, '；')
                one = cls.mb_rtrim(one, '，')
                tmp = XlxAdminLog(admin_id=admin_info.id, admin_name=admin_info.username, content=one, is_login=is_login, addtime=int(time.time()), ip=ip, ip_addr=ip_addr, type=type)
                log_all.append(tmp)
            return cls.saveAll(log_all)
        else:
            content = content.strip()
            content = cls.mb_rtrim(content, '；')
            content = cls.mb_rtrim(content, '，')
            data = XlxAdminLog(admin_id=admin_info.id, admin_name=admin_info.username, content=content, is_login=is_login, addtime=int(time.time()), ip=ip, ip_addr=ip_addr, type=type)
            return cls.save(data)

    @classmethod
    def save(cls, data: XlxAdminLog):
        with getDatabaseSession() as session:
            session.add(data)
            session.commit()
            session.refresh(data)

        return data

    @classmethod
    def saveAll(cls, data: list[XlxAdminLog]):
        with getDatabaseSession() as session:
            session.bulk_save_objects(data)

    @classmethod
    def mb_rtrim(cls, str_value, char):
        if not str_value:
            return ''

        # 使用encode和decode来处理多字节字符（这里假设是UTF-8编码）
        # 注意：这种方法可能不适用于所有多字节字符集，但它对UTF-8通常是足够的
        str_bytes = str_value.encode('utf-8')
        char_bytes = char.encode('utf-8')

        # 使用while循环来移除末尾的字符，直到不再匹配为止
        while str_bytes and str_bytes.endswith(char_bytes):
            str_bytes = str_bytes[:-len(char_bytes)]

        # 将处理后的字节串转回字符串
        return str_bytes.decode('utf-8')
